package p05_BeanFactory后处理器;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import p05_BeanFactory后处理器.component.Bean1;
import p05_BeanFactory后处理器.component.Bean2;
import p05_BeanFactory后处理器.component.Bean3;
import p05_BeanFactory后处理器.mapper.Mapper1;

@Configuration
@ComponentScan(basePackages = "p05_BeanFactory后处理器.component")
public class Config {

    @Bean(initMethod = "init")
    public Bean1 bean1() {
        return new Bean1();
    }

    @Bean
    public Object bean2(Bean1 bean1) {
        return new Bean2();
    }

    public Object bean3() {
        return new Bean3();
    }

    @Bean
    public PooledDataSource dataSource() {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("220600");
        return dataSource;
    }

    /**
     * 工厂bean，这种bean负责创建其他bean
     * 这种工厂bean创建SqlSessionFactory对象并放入容器
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(PooledDataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    /**
     * MapperFactoryBean可以根据Mapper接口创建Mapper对象放入容器(动态代理)
     * 下面演示生成Mapper1接口的对象
     */
    @Bean
    public MapperFactoryBean<Mapper1> mapper1(SqlSessionFactory sqlSessionFactory) {
        MapperFactoryBean<Mapper1> factoryBean = new MapperFactoryBean<>(Mapper1.class);
        //Mapper1的实现类将来是要去查数据库的，所以需要赋予一个数据源(sqlSessionFactory)
        factoryBean.setSqlSessionFactory(sqlSessionFactory);
        return factoryBean;
    }

}
